# src/utils/youtube_client.py

from itertools import cycle
import logging
from googleapiclient.discovery import build

# 模块级变量
key_pool = None
current_key = None

def initialize_api_key_rotator(api_keys):
    """
    初始化 API Key 轮换器
    :param api_keys: API 密钥列表
    """
    global key_pool, current_key
    if not api_keys or len(api_keys) == 0:
        raise ValueError("❌ API Keys 不能为空")

    key_pool = cycle(api_keys)
    current_key = next(key_pool)
    logging.info(f"🔁 API Key 轮换器已初始化，当前使用 Key: {current_key[:10]}...")

def get_youtube_service():
    """
    获取当前可用的 YouTube 客户端
    """
    global key_pool

    if key_pool is None:
        raise RuntimeError("❌ API Key 轮换器未初始化，请先调用 initialize_api_key_rotator()")

    current_key = next(key_pool)
    return build('youtube', 'v3', developerKey=current_key)